import {
    findByCity,getProjectPermission,changeStatus,editFun,deleteFun,exportPdf
    } from './monthReportServ'
    // import { parse } from 'qs'
    import { message } from 'antd'
    import { request } from 'config/request'
    // import moment from 'moment'
    import config from 'config/config'
    import axios from 'axios'
    import { rstr2b64 } from '../../../../utils/md5'
    import { download, makeAddress } from 'utils/util'
    import $ from 'jquery'
    import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
    
    const defultState = {
        biz:{
          queryForm: {}
        },
        biz1: {
          queryForm: {}
        },
        biz2: {
          queryForm: {}
        },
        url: '',
        btnLoading: false,
        visible: false,
        tabsType: '',
        areaList: [],
        cityList: [],
        id:"",
        talkWayModal: {
          visible : false
        },
        zituoQuery: { //拓客方式
          id: '',
          methodName: '',
        },
        otherQuery:{
          areaId:"",
          projectId:""
        },
        exportXlsFlag: false
    }
    
    const tmpModule = {
      state: cloneDeep(defultState),
      subscriptions: {
        setup ({dispatch, history}) {
          history.listen(({ pathname, query }) => {
            if('' + tmpModule.pathname === '' + pathname){
              dispatch({type: 'updateStore', payload: cloneDeep(defultState)});
              dispatch({type: 'getProjectPermission', payload: {tabsType:query.tabsType}})
            }
          })
        },
      },
    
      effects: {
        //获取区域项目
        *getProjectPermission({payload}, {put, select, call}){
          let {areaList,tabsType} = yield select(state => state[tmpModule.namespace])
          let subElements =  JSON.parse(localStorage.navBar).subElements
          if(subElements.includes(170501)){
            tabsType = '1'
          }
          if(!subElements.includes(170501)&&subElements.includes(170502)){
            tabsType = '2'
          }
          if(payload.tabsType){
            tabsType = payload.tabsType
          }
            let params = { 
              userId: localStorage.username
            }
            const { success,projectList} = yield call(getProjectPermission, {...params})
            areaList =  projectList.map((item,index)=>{
                          return {
                            label: item.areaName,
                            value: item.areaId,
                          }
                        })
              yield put({
                type: 'updateStore',
                payload: {areaList,tabsType}
              })
            if(subElements.includes(170501)){
              $(".configuration-center-tabs .ant-tabs-tab").eq(0).css('display','inline-block');
            }else{
              $(".configuration-center-tabs .ant-tabs-tab").eq(0).css('display','none');
            }
            if(subElements.includes(170502)){
              $(".configuration-center-tabs .ant-tabs-tab").eq(1).css('display','inline-block');
            }else{
              $(".configuration-center-tabs .ant-tabs-tab").eq(1).css('display','none');
            }
        },
        *submitContent({payload},{put,select,call}){
          let {biz1,btnLoading} = yield select(state => state[tmpModule.namespace])
          if(payload.type=="集团"){
            if(payload.params.status=='0'){
              let arr=[];
              if(localStorage.getItem("thisTime")){
                console.log(JSON.parse(localStorage.getItem("thisTime")),'[[[[')
                arr=JSON.parse(localStorage.getItem("thisTime"))
                arr.push({
                  time:new Date().getTime(),
                  id:payload.params.id
                });
              }else{
                arr.push({
                  time:new Date().getTime(),
                  id:payload.params.id
                });
              }
              localStorage.setItem("thisTime",JSON.stringify(arr));
              request({
                url: `${config.aheadPlan}admin/groupMonth/groupMonth/exportPdf?id=${payload.params.id}`,
                method: 'POST',
              });
            };
            let params = {
              id: payload.params.id,
              status: payload.params.status=='1'?'0':'1',
              updateBy:localStorage.nickname,
              updateUser:localStorage.username,
              month: payload.params.month,
              title: payload.params.title
            }
            const { success, msg, data } = yield call(changeStatus, {...params})
            let defultState = yield select(state => state[tmpModule.namespace])
            if(success){
              message.success('操作成功')
              defultState.biz2.refreshListDatas(true)
            }
          }
          if(payload.type=="市场"){
            let params = {
              id: payload.params.id,
              monthlyStatus: payload.params.monthlyStatus=='1'?'0':'1',
              updateBy:localStorage.nickname,
              updateUser:localStorage.username
            }
            const { success, msg, data } = yield call(editFun, {...params})
            let defultState = yield select(state => state[tmpModule.namespace])
            if(success){
              message.success('操作成功')
              defultState.biz1.refreshListDatas(true)
            }
          }
          if(payload.type=="多选提交"){
            if(biz1.selectedRows.length==0){
              message.warning('请先选择要提交的数据')
              return
            }
            let arr = []
            for(var item of biz1.selectedRows){
              arr.push(item.id)
            }
            let params = {
              id: arr.join(','),
              monthlyStatus: '1',
              updateBy:localStorage.nickname,
              updateUser:localStorage.username
            }
            btnLoading = true
            yield put({type: 'updateStore', payload: {btnLoading}})
            const { success, msg, data } = yield call(editFun, {...params})
            let flag = success.toString()
            if(flag){
              btnLoading = false
              yield put({type: 'updateStore', payload: {btnLoading}})
            }
            let defultState = yield select(state => state[tmpModule.namespace])
            if(success){
              message.success('操作成功')
              defultState.biz1.refreshListDatas(true)
            }
          }
        },
        *deleteFun({payload}, {put, select, call}){
          let params = {
            id: payload.params.id
          }
          const { success, msg, data } = yield call(deleteFun, params)
          let defultState = yield select(state => state[tmpModule.namespace])
          if(success){
            message.success('操作成功')
            defultState.biz1.refreshListDatas(true)
          }
        },
        *exportXls({payload},{put,select,call}){
          if(payload.item.status=='0'){
            return message.warning('请先发布再导出');
          }
          let array=localStorage.getItem("thisTime");
          let time=null;
          if(array){
            let arr;
            arr=JSON.parse(array);
            arr.map((item,index)=>{
              if(item.id==payload.item.id){
                time=item.time;
              }
            });
          };
          if(!time||new Date().getTime()-time>300000){
            let month = payload.item.month.split('-')[1];
          if (month.indexOf('0') != -1) {
            month = month.split('0')[1]
          }
          let param = `${config.shenzhenUrl}/美的置业-${month}月市场量价走势月报.pdf` || ''
          var saveAs = function (blob, filename) {
            var URL = window.URL || window.webkitURL;
            var type = blob.type;
            var force_saveable_type = 'application/octet-stream';
            if (type && type != force_saveable_type) { // 强制下载，而非在浏览器中打开
              var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
              blob = slice.call(blob, 0, blob.size, force_saveable_type);
            }
            var url = URL.createObjectURL(blob);
            var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
            save_link.href = url;
            save_link.download = filename;
    
            var event = new MouseEvent("click", {
              bubbles: true,
              cancelable: true,
              view: window
            });
            save_link.dispatchEvent(event);
            URL.revokeObjectURL(url);
          }
          var oReq = new XMLHttpRequest();
          var URLToPDF = param;
            oReq.open("GET", URLToPDF, true);
            oReq.responseType = "blob";
            oReq.onload = function () {
              var file = new Blob([oReq.response], { type: 'application/pdf' });
              console.log(oReq.response,'123')
              saveAs(file, `美的置业-${month}月市场量价走势月报.pdf`);
            };
            oReq.send();
          }else{
            message.success('还未生成,请发布完5分钟之后再导出')
          }
        },
        *findByCity({payload}, {put, select, call}){
          let {cityList} = yield select(state => state[tmpModule.namespace])
          let params = { 
            area: payload.areaId,
          }
          const { success,result} = yield call(findByCity, {...params})
          if(success){
            let list = result.filter(item => !!item)
            cityList =  list.map((item,index)=>{
                        return {
                          label: item.city,
                          value: item.cityid,
                        }
                      })
            yield put({
              type: 'updateStore',
              payload: {cityList}
            })
          }
        },
      },
      // 存入状态机
      reducers: {
        updateStore(preState, action) {
          return Object.assign({}, preState, action.payload)
        },
      }
    }
    
    export default tmpModule
    